import React, { useEffect, useState } from 'react';
import { history, useSelector } from 'umi';
import { queryPayInfo } from '@/services/order';
import ResultSvg from './components/ResultSvg';
import { Message, Price } from '@/design';
import { isEmpty, payWayName } from '@/utils/common';
import styles from './payment.less';

export default function (props: any) {

  let unmount = false;
  const { payhold } = useSelector((state: any) => state.payment);
  const [orderInfo, setOrderInfo] = useState<any>({});
  const braId = localStorage.getItem('BRAID');
  let codeId = localStorage.getItem('CODEID');

  /* 查詢支付信息 */
  const fetchPayInfo = async () => {
    console.log('fetchPayInfo--------', payhold)
    if (isEmpty(payhold.orderId)) {
      console.log('payholdpayhold', payhold)
      // return history.replace('/order');
    }
    if (!payhold.orderId) {
      // return Message.error('未查詢到有效支付信息') 
      return false
    }
    //applepay、cardpay、linepay lineOrderId是orderId  其他的话是orderNo（订单返回的）
    let result = await queryPayInfo({lineOrderId: payhold.orderId , payWay: payhold.payWay });
    if (unmount || !result) return;
    setOrderInfo(payhold);
  }

  /* 我的訂單 */
  const linkToOrder = () => {
    history.replace(`/orderlist`)
  }

  /* 訂單詳情 */
  const linkToDetail = () => {
    history.replace(`/orderdetail?orderNo=${orderInfo.orderId}`)
  }

  useEffect(() => {
    fetchPayInfo();
    const { braId } = props.location.query;
    if (!isEmpty(braId)) {
      localStorage.setItem('BRAID', braId)
    }
    return () => {
      unmount = true;
    }
  }, [payhold])

  const handleJump = (toUrl: string) => {
    if(toUrl === 'DETAIL') {
      return history.push(`/orderdetail?orderNo=${orderInfo.orderId}`)
    }
    if(toUrl === 'HOME') {
      return  history.push(`/home?braId=${braId}&codeId=${codeId}`);
    }
  }

  return !isEmpty(orderInfo) ? <div className={styles.result_wrap}>
    {/* <ResultSvg status="success" /> */}
    <div className={styles.result_header}>
      <a onClick={linkToOrder}>我的訂單</a>
    </div>
    <div className={styles.result_flex}>
      <div className={styles.result_store}>
        <a >{orderInfo.braName}</a>
      </div>
      <div className={styles.result_icons}><ResultSvg status={orderInfo.orderStatus === 'unpay' ? 'fail' : 'success'} /></div>
      <div className={styles.result_price}>
        <i className={styles.pay_status}>{orderInfo.orderStatus === 'unpay' ? '交易失敗' : '收款成功'}</i>
        <p><Price price={orderInfo.orderAmount} /></p>
      </div>
      {/* <a className={styles.result_shopping} >返回首頁</a> */}
      <a className={styles.result_invoice} >紙本發票</a>
      <a className={styles.result_invoice_detail} href={'/invoice'}>查看發票詳情</a>
      <button className={styles.to_index} onClick={()=> {handleJump('HOME')}}>返回首頁</button>
      <button className={styles.to_order_detail} onClick={()=> {handleJump('DETAIL')}}>查看訂單詳情</button>
    </div>
   
  </div> : <></>
}